<script setup lang="ts">
import { ElMessageBox } from 'element-plus';
import { useWindowInnerSize } from 'my-vue-core/composables';
import { User } from 'my-web-core/models';
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';

import router from '../../app-router';
import UserService from './user-service';

const EditUser = defineAsyncComponent(() => import('./EditUser.vue'));
const tableSize = useWindowInnerSize({ heightOffset: 260 });
const data = ref<User[]>([]);
const rowSelection = ref<boolean>(false);
const selectedIds = ref<string[]>([]);
const dialogVisible = ref<boolean>(false);
const pageSizeSetting = ref<number[]>([10, 20, 50, 100]);
const table = ref(null);

const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0,
});

onMounted(() => {
  query();
});

async function query(): Promise<void> {
  data.value = await UserService.queryAccountGroupUsers(
    pagination.pageSize!,
    pagination.currentPage,
  );

  // TODO: Uses real number returned from api.
  pagination.total = 200;
}

function toggleRowSelection(): void {
  rowSelection.value = !rowSelection.value;

  if (!rowSelection.value) {
    (table.value as any).clearSelection();
    selectedIds.value = [];
  }
}

function handleSelectionChange(selection: User[]): void {
  selectedIds.value = selection.map((p) => p.id!);
}

function handleSizeChange(val: number): void {
  pagination.pageSize = val;
  query();
}

function handleCurrentChange(val: number): void {
  pagination.currentPage = val;
  query();
}

function reload(): void {
  pagination.currentPage = 1;
  query();
}

function onOk(): void {
  reload();
  dialogVisible.value = false;
}

function deleteData(): void {
  ElMessageBox.confirm(`删除所选 ${selectedIds.value.length} 项数据吗？`, '确认删除？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      await UserService.delete(selectedIds.value);
      reload();
    })
    .catch(() => {});
}
</script>

<template>
  <div class="table-container">
    <div class="action-container">
      <el-space>
        <el-button type="primary" @click="dialogVisible = true">添加</el-button>
        <el-button @click="toggleRowSelection">{{ rowSelection ? '取消' : '选择' }}</el-button>
        <el-button
          type="danger"
          v-if="rowSelection"
          @click="deleteData"
          :disabled="selectedIds.length === 0"
          >删除
        </el-button>
      </el-space>
    </div>
    <el-table
      ref="table"
      :data="data"
      @selection-change="handleSelectionChange"
      row-key="id"
      :height="tableSize.height"
      stripe
      fit
    >
      <el-table-column v-if="rowSelection" type="selection" width="55" key="selection" />
      <el-table-column fixed label="操作" width="100">
        <template #default="scope">
          <el-button size="small" @click="router.push(`/user/detail/${scope.row.id}`)"
            >详情</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="头像" width="80">
        <template #default="scope">
          <el-avatar :src="scope.row.avatarUrl" />
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="130" />
      <el-table-column prop="fullName" label="昵称" />
    </el-table>
    <el-pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      v-model:currentage="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="pageSizeSetting"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
  <el-dialog v-model="dialogVisible" title="添加用户" width="30%">
    <EditUser @ok="onOk" @cancel="() => (dialogVisible = false)" />
  </el-dialog>
</template>

<style scoped>
.table-container {
  display: flex;
  flex-direction: column;
  align-items: end;
}

.action-container {
  display: flex;
  flex-direction: row;
  width: 100%;
  margin-bottom: 20px;
}

.el-table {
  width: 100%;
}

.el-pagination {
  margin-top: 20px;
  padding: 0px;
}
</style>
